//获取token
window.onload=setTimeout("welcome()",1000);
function welcome() {
    var storage = window.localStorage;
    var user = storage.getItem("data");
    console.log(user);
    var user = JSON.parse(user);
    var username = user.user.userId;

    document.getElementById("username").innerHTML = username;
    console.log(username)
}
//获取所有商品信息并赋值给相应的元素
function getData() {
    $.ajax({
        type: "get",
        url: "/common/goods/list",
        contentType: "application/json;charset=UTF-8",
        dataType: "json",
        // data:data,
        success(res) {
            console.log(res.msg)
            if (2000 == res.code) {
                var goods = res.data.goods
                console.log(goods);
                //接收URL中的参数booksId
                var id = getUrlParam('goodsId');
                console.log('id:'+id);
                for(i=0;i<goods.length;i++){
                    if(id==goods[i].id){
                        var supplier_name=document.getElementById("supplier")
                        var goods_name=document.getElementById("goods_name")
                        var city=document.getElementById("city")
                        // var stock=document.getElementById("stock")
                        var description=document.getElementById("goods_descrip")
                        var category=document.getElementById("goods_category")
                        var store_price=document.getElementById("store_price")
                        var price=document.getElementById("price")
                        // var start_time=document.getElementById("start_time")
                        // var end_time=document.getElementById("end_time")
                        var goods_img=document.getElementById("goods_img")
                        // var goods_link=document.getElementById("goods_link")
                        // var time1 = datetime(goods[i].startTime);
                        // var time2 = datetime(goods[i].endTime);
                        // times=goods[i].startTime;//开始毫秒数
                        // timee=goods[i].endTime;//结束毫秒数;
                        supplier_name.innerHTML=goods[i].supplierName
                        goods_name.innerHTML=goods[i].goodsName
                        city.innerHTML=goods[i].city
                        // stock.innerHTML=goods[i].stock
                        description.innerHTML=goods[i].description
                        category.innerHTML=goods[i].category
                        store_price.innerHTML=goods[i].storePrice
                        price.innerHTML=goods[i].price
                        // start_time.innerHTML=time1
                        // end_time.innerHTML=time2
                        goods_img.src=goods[i].imgPath
                        // goods_link.href=goods[i].imgPath
                    }
                }
            }
        }
    })
}

//计算功能
function sum() {
    var single_price = document.getElementById("price")
    var goods_count = document.getElementById("number")
    var sum = document.getElementById("count")
    var sum2=document.getElementById("sum2")
    sum.innerHTML = parseInt(single_price.innerHTML) * goods_count.value
    sum2.innerHTML=sum.innerHTML
}
//获取地址栏url中的参数，得到上一页传过来的id值
function getUrlParam(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
    var r = window.location.search.substr(1).match(reg); //匹配目标参数
    if (r != null) return unescape(r[2]); return null; //返回参数值
}
//结算
function pay(){
    var id=getUrlParam("goodsId")
    var name=document.getElementById("goods_name").innerHTML
    var price=document.getElementById("price").innerHTML
    var quantity=document.getElementById("number").value
    //用户ID
    var storage = window.localStorage;
    var user = storage.getItem("data");
    var user = JSON.parse(user);
    var temp = user.user.userId;

    var item = new Object();
    item.goodsId=id
    item.goodsName=name
    item.currentUnitPrice=price
    item.quantity=quantity
    item.userId=temp

    var list = [];
    list.push(item);

    $(function(){
        $.ajax({
            type:"post",
            url:"/order",
            contentType: "application/json",
            data:
                //"userId":userId,
                JSON.stringify(list)
            ,
            dataType :"json",
            success:function(res){
                var data = {
                    userId: temp,
                    orderId: res.data.orderId
                };
                var json_data = JSON.stringify(data);
                console.log(json_data);
                $.ajax({
                    type:"post",
                    url:"/order/pay.do",
                    contentType: "application/json",
                    data: json_data,
                    success: function (res) {
                        console.log(res);
                        var payDiv=document.getElementById("payDiv")
                        var cartDiv=document.getElementById("cartDiv")
                        cartDiv.style.display="none"
                        payDiv.style.display="block"

                        if(res.status="0") {
                            console.log(res);
                            var orderhtml=" ";
                            var orderhtml ="<center><p>订单提交成功，请您尽快支付！ 订单号："+res.data.orderId+"</p >"+
                                           "<p>请使用支付宝扫描如下二维码进行支付：</p >"+
                                           "<div><img src="+"/image/upload/"+res.data.qrUrl+"><br/>"+
                                           "<button onclick='showCart()'>返回购物车</button>"+
                                           "</div></center>"
                            $("#payDiv").append(orderhtml);
                        }
                        setTimeout("showSuccess()",5000)//demo-支付成功
                        setTimeout("toHome()",5000)
                    },
                });
            },
            error: function (XMLHttpRequest, textStatus, errorThrown){
                alert("error");
            }
        });
    });
}
function showCart() {
    var payDiv=document.getElementById("payDiv")
    var cartDiv=document.getElementById("cartDiv")
    cartDiv.style.display="block"
    payDiv.innerHTML=" "
}

//显示支付成功-demo
function showSuccess(){
    var payDiv=document.getElementById("payDiv")
    var successDiv=document.getElementById("success")
    successDiv.style.display="block"
    payDiv.innerHTML=" "
}
//定时函数
function toHome(){
    var timeDiv=document.getElementById("timeDiv")
    var timerun=5
    timeDiv.innerHTML=timerun
    var interval=setInterval(function () {
        timerun-=1
        timeDiv.innerHTML=timerun
        if(timerun===0){
            location.assign("home.html")
            clearInterval(interval)
            timerun=5
        }
    },1000)
}


//运行函数
window.onload=setTimeout("getData()",10);
setInterval("sum()","1000")